package com.gitee.elead.web.utli;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import com.gitee.elead.web.FileType;

public class FileUploadUtils {

	/**
	 * Part of HTTP content type header.
	 */
	public static final String MULTIPART = "multipart/";

	/**
	 * <p>
	 * Utility method that determines whether the request contains multipart
	 * content.
	 * </p>
	 *
	 * <p>
	 * <strong>NOTE:</strong>This method will be moved to the
	 * <code>ServletFileUpload</code> class after the FileUpload 1.1 release.
	 * Unfortunately, since this method is static, it is not possible to provide its
	 * replacement until this method is removed.
	 * </p>
	 *
	 * @param request The request context to be evaluated. Must be non-null.
	 *
	 * @return <code>true</code> if the request is multipart; <code>false</code>
	 *         otherwise.
	 */
	public static final boolean isMultipartContent(HttpServletRequest request) {
		String contentType = request.getContentType();
		if (contentType == null) {
			return false;
		}
		if (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断文件是图片格式
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static FileType getFileType(InputStream is) throws IOException {
		byte[] src = new byte[28];
		is.read(src, 0, 28);
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v).toUpperCase();
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		FileType[] fileTypes = FileType.values();
		for (FileType fileType : fileTypes) {
			if (stringBuilder.toString().startsWith(fileType.getValue())) {
				return fileType;
			}
		}
		return null;
	}

}
